package com.gzw.jackyweather;


import android.Manifest;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.util.CircularIntArray;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gzw.jackyweather.db.CityManger;
import com.gzw.jackyweather.db.CityWeatherInfo;
import com.gzw.jackyweather.db.Skin;
import com.gzw.jackyweather.gson.Forecast;
import com.gzw.jackyweather.gson.Weather;
import com.gzw.jackyweather.service.AutoUpdateService;
import com.gzw.jackyweather.service.DownLoadService;
import com.gzw.jackyweather.util.HttpUtil;
import com.gzw.jackyweather.util.Utility;
import com.gzw.jackyweather.weight.AutoDrawLayout;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends BaseActivity {

    private ScrollView sl_weather;
    private ImageView iv_backGround;

    public SwipeRefreshLayout srl;
    public AutoDrawLayout dl;
    private Button btn_nav;
    private Button btn_photo;


    private TextView tv_title_city;
    private TextView tv_update_time;
    private TextView tv_degree;
    private TextView tv_weather_info;
    private LinearLayout ll_forecast;

    private TextView tv_aqi;
    private TextView tv_pm25;

    private TextView tv_comfor;
    private TextView tv_carWash;
    private TextView tv_sport;

    private long exitTime = 0;

    private String hisweatherId;//历史的天气ID

    private boolean fromBiY = true;//图片是否来自必应

    private DownLoadService.DownLoadBinder binder;

    //绑定服务和解除绑定的时候调用
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (DownLoadService.DownLoadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    public int getContentViewID() {
        return R.layout.activity_weather;
    }

    @Override
    protected void initView() {

        sl_weather = (ScrollView) findViewById(R.id.sl_weather);
        iv_backGround = (ImageView) findViewById(R.id.iv_background);

        srl = (SwipeRefreshLayout) findViewById(R.id.srl);
        srl.setColorSchemeResources(R.color.colorPrimary);
        dl = (AutoDrawLayout) findViewById(R.id.dl);
        btn_nav = (Button) findViewById(R.id.btn_nav);
        btn_photo = (Button) findViewById(R.id.btn_photo);

        btn_nav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dl.openDrawer(GravityCompat.START);
            }
        });


        Intent intent = new Intent(this, DownLoadService.class);
        startService(intent);
        bindService(intent, connection, BIND_AUTO_CREATE);

        //获取默认图片
        List<Skin> skins = DataSupport.where("isDefault = ?", "1").find(Skin.class);
        if (skins.size() != 0) {
            if (skins.get(0).getImgId() == 0) {
                Glide.with(WeatherActivity.this).load(skins.get(0).getFlag()).into(iv_backGround);
            } else {
                iv_backGround.setImageResource(skins.get(0).getImgId());
            }
        }

        //长按下载更新
//        btn_nav.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//
//                if (binder != null) {
//                    binder.startDownLoad(Contans.APK_URL);
//                }
//
//                return true;
//            }
//        });
//
//        btn_photo.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                String downLoadUrl = Contans.APK_URL;
//                String fileName = downLoadUrl.substring(downLoadUrl.lastIndexOf("/"));
//                String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
//                File file = new File(directory + fileName);
//                if (file.exists()) {
//                    file.delete();
//                }
//                return true;
//            }
//        });

        btn_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //获取权限
                if (ContextCompat.checkSelfPermission(WeatherActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(WeatherActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    //更换被背景,打开相册
                    selectImage();
                }
            }
        });

        tv_title_city = (TextView) findViewById(R.id.tv_title_city);
        tv_update_time = (TextView) findViewById(R.id.tv_update_time);
        tv_degree = (TextView) findViewById(R.id.tv_degree);
        tv_weather_info = (TextView) findViewById(R.id.tv_weather_info);
        ll_forecast = (LinearLayout) findViewById(R.id.ll_forecast);

        tv_aqi = (TextView) findViewById(R.id.tv_aqi);
        tv_pm25 = (TextView) findViewById(R.id.tv_pm25);

        tv_comfor = (TextView) findViewById(R.id.tv_comfort);
        tv_carWash = (TextView) findViewById(R.id.tv_car_wash);
        tv_sport = (TextView) findViewById(R.id.tv_sport);


        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

//        String bingPic = sp.getString("bing_pic", null);
//        if (bingPic != null) {
//            System.out.println("图片" + bingPic);
//
//            if (bingPic.substring(0, 4).equals("http")) {
//                Glide.with(this).load(bingPic).into(iv_backGround);
//                fromBiY = true;
//            } else {
//                Uri uri = Uri.parse(bingPic);
//                Glide.with(this).load(uri).into(iv_backGround);
//                fromBiY = false;
//            }
////            iv_backGround.setImageResource(R.mipmap.background);
//        } else {
//            loadBingPic();
//        }

        //加载天气数据
        loadWeatherData();

//        String weatherString = sp.getString("weather", null);
//        if (weatherString != null) {
//            //有缓存就直接解析天气数据
//            Weather weather = Utility.handleWeatherResponse(weatherString);
//            hisweatherId = weather.basic.weatherId;
//            showWeatherInfo(weather);
//        } else {
//            //获取服务器天气数据
//            hisweatherId = getIntent().getStringExtra("weather_id");
//            sl_weather.setVisibility(View.INVISIBLE);
//            requestWeather(hisweatherId);
//        }

        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(hisweatherId);
            }
        });
    }

    //加载天气数据
    private void loadWeatherData() {

        //查询表中有没有默认的城市，如果有，就直接加载数据，如果没有，就加载服务器数据
        List<CityManger> mangers = DataSupport.where("isDefault = ?", "1").find(CityManger.class);
        if (mangers.size() != 0) {
            List<CityWeatherInfo> infos = DataSupport.where("weather_id=?", mangers.get(0).getWeather_id()).find(CityWeatherInfo.class);
            Weather weather = Utility.handleWeatherResponse(infos.get(0).getWeather_info());
            hisweatherId = weather.basic.weatherId;
            showWeatherInfo(weather);

        } else {
            //获取服务器天气数据
            hisweatherId = getIntent().getStringExtra("weather_id");
            sl_weather.setVisibility(View.INVISIBLE);
            requestWeather(hisweatherId);
        }
    }

    /**
     * 获取必应的每日一图
     */
    private void loadBingPic() {

        if (fromBiY) {
//            String requestBingPic = "http://guolin.tech/api/bing_pic/";
            HttpUtil.sendOkHttpRequest(Contans.IMG_URL, new Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    //保存请求的图片
                    final String json = response.body().string();
                    String imgurl = null;
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        imgurl = jsonObject.getString("img");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    final String bingPic = imgurl;

                    SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                    edit.putString("bing_pic", bingPic);
                    edit.apply();
                    fromBiY = true;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Glide.with(WeatherActivity.this).load(bingPic).into(iv_backGround);
                        }
                    });
                }

                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    /**
     * 获取服务器天气数据
     *
     * @param weatherId
     */
    public void requestWeather(final String weatherId) {

        String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId +
                "&key=" + Contans.KEY;

        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String responseText = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather != null && "ok".equals(weather.status)) {


                            List<CityWeatherInfo> infos = DataSupport.where("weather_id=?", hisweatherId).find(CityWeatherInfo.class);
                            //查询数据库中的数据，如果没有就添加，如果有就更新
                            if (infos.size() != 0) {
                                ContentValues values = new ContentValues();
                                values.put("weather_info", responseText);
                                DataSupport.updateAll(CityWeatherInfo.class, values, "weather_id = ?", weatherId);
                            } else {
                                CityWeatherInfo info = new CityWeatherInfo();
                                info.setWeather_id(hisweatherId);
                                info.setWeather_info(responseText);
                                info.save();
                            }


//                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
//                            editor.putString("weather", responseText);
//                            editor.apply();


                            hisweatherId = weather.basic.weatherId;
                            showWeatherInfo(weather);

                            List<CityManger> cityMangers = DataSupport.where("weather_id = ?", weather.basic.weatherId).find(CityManger.class);
                            if (cityMangers.size() == 0) {
                                //说明没有数据，添加一条数据

                                CityManger manger = new CityManger();
                                manger.setDefault(true);
                                manger.setWeather_id(weather.basic.weatherId);
                                manger.setCityName(weather.basic.cityName);
                                manger.setDegree(weather.now.temperature + "℃");
                                manger.setWeather_info(weather.now.more.info);
                                manger.save();

                            } else {
                                //有数据，更新一条数据
                                ContentValues values = new ContentValues();
                                values.put("degree", weather.now.temperature + "℃");
                                values.put("cityName", weather.basic.cityName);
                                values.put("weather_info", weather.now.more.info);
                                DataSupport.updateAll(CityManger.class, values, "weather_id = ?", weather.basic.weatherId);
                            }

                            //开启一个服务，每8小时更新一次天气数据
                            Intent intent = new Intent(WeatherActivity.this, AutoUpdateService.class);
                            startService(intent);

                        } else {
                            Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        }
                        srl.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onFailure(Call call, IOException e) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        srl.setRefreshing(false);
                    }
                });
            }
        });

//        loadBingPic();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        loadWeatherData();
        List<Skin> skin = DataSupport.where("isDefault = ?", "1").find(Skin.class);
        if (skin.size() != 0) {
            if (skin.get(0).getImgId() == 0) {
                Glide.with(WeatherActivity.this).load(skin.get(0).getFlag()).into(iv_backGround);
            } else {
                iv_backGround.setImageResource(skin.get(0).getImgId());
            }
        }
    }

    public void showWeatherInfo(Weather weather) {

        String cityName = weather.basic.cityName;
        String updateTime = weather.basic.update.updateTime.split(" ")[1];
        String degree = weather.now.temperature + "℃";
        String weatherInfo = weather.now.more.info;

        tv_title_city.setText(cityName);
        tv_update_time.setText(updateTime);
        tv_degree.setText(degree);
        tv_weather_info.setText(weatherInfo);

        ll_forecast.removeAllViews();

        for (Forecast forecast : weather.forecastList) {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, ll_forecast, false);
            TextView tv_date = (TextView) view.findViewById(R.id.tv_date);
            TextView tv_info = (TextView) view.findViewById(R.id.tv_info);
            TextView tv_max = (TextView) view.findViewById(R.id.tv_max);
            TextView tv_min = (TextView) view.findViewById(R.id.tv_min);

            tv_date.setText(forecast.date);
            tv_info.setText(forecast.more.info);
            tv_max.setText(forecast.temperature.max);
            tv_min.setText(forecast.temperature.min);

            ll_forecast.addView(view);
        }

        if (weather.aqi != null) {
            tv_aqi.setText(weather.aqi.city.aqi);
            tv_pm25.setText(weather.aqi.city.pm25);
        }

        String comfort = "舒适度：" + weather.suggestion.comfort.info;
        String carWash = "洗车指数：" + weather.suggestion.carWash.info;
        String sport = "运动建议：" + weather.suggestion.sport.info;

        tv_comfor.setText(comfort);
        tv_carWash.setText(carWash);
        tv_sport.setText(sport);
        sl_weather.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                System.exit(0);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private final int IMAGE_CODE = 0;
    Uri bitmapUri = null;
    private final String IMAGE_TYPE = "image/*";

    //获取相册的图片
    private void selectImage() {
        Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        getAlbum.setType(IMAGE_TYPE);
        startActivityForResult(getAlbum, IMAGE_CODE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE_CODE:
                    Uri originalUri = data.getData();  //获得图片的uri
                    bitmapUri = originalUri;
                    //使用Glide加载图片
                    Glide.with(this).load(bitmapUri).into(iv_backGround);

                    SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                    edit.putString("bing_pic", bitmapUri.toString());
                    edit.apply();
                    fromBiY = false;
                    break;
            }
        }
    }

    //申请权限的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    selectImage();
                } else {
                    Toast.makeText(this, "你需要打开权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    public void closeDraw() {
        dl.closeDrawer(GravityCompat.START);
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeDraw();
    }
}
